<?php
/**
 * CrontabController.class.php
 * 定时任务控制器
 *
 * @author  王中艺
 * @date    2016-11-24
 */

namespace Wechat\Controller;
use Think\Controller;

class CrontabController extends Controller {

    private     $lockName;

    function _initialize(){
        //检测进程锁
        $this->lockName     = 'crontab_lock_'.ACTION_NAME;
        //调试
        S($this->lockName, null);
        if(S($this->lockName)){
            echo 'process is executing!';
            exit;
        }
        S($this->lockName, 1, 3600*4);
        //设置为不超时
        set_time_limit(0);
    }

    /**
     * 定时上线幸福语录
     * 每5分钟运行一次
     */
    function onlineMotto(){
        // $list   = D('Motto')->where('status = 2 and online_time <= %d', time())->select();
        // foreach($list as $item){
        //     try{
        //         $item['status'] = 1;
        //         D('Motto')->save($item);
        //     }catch(\Exception $e){
        //         write_log('./Log/crontab_error.log', $this->lockName, $item);
        //     }
        // }
    }

    /**
     * 清除过期VIP
     * 每天运行一次
     */
    function clearInvalidVip(){
        try{
            $count  = M('t_user', null)
                ->where('vip_endtime < %d', time())
                ->save(['vip_level' => 0]);

            write_log('./Log/crontab.log', 'ClearInvalidVip', ['count' => $count]);
        }catch(\Exception $e){
            write_log('./Log/error.log', 'Crontab:ClearInvalidVip', $e->getMessage);
        }
        S($this->lockName, null); 
    }

    /**
     * 用户儿童年纪提升
     * 每年09.01执行
     */
    function childLevelUp(){
        try{
            $count3     = M('t_user', null)
                ->where('child_level = 2')
                ->save(['child_level' => 3]);

            $count2     = M('t_user', null)
                ->where('child_level = 1')
                ->save(['child_level' => 2]);

            write_log('./Log/crontab.log', 'ChildLevelUp',[
                'to_level2' => $count2,
                'to_level3' => $count3
            ]);
        }catch(\Exception $e){
            write('./Log/error.log','Crontab:ChildLevelUp', $e->getMessage);
        }

        S($this->lockName, null); 
    }

    /**
     * VIP即将到期提醒
     * 每天执行一次
     */
    function notifyVipWillEnd(){
        try{
            $timeS  = strtotime(date('Y-m-d').' +30 day');
            $timeE    = $timeS + 3600*24;
            $list   = M('t_user', null)
                ->where('vip_endtime >= %d and vip_endtime < %d', $timeS, $timeE)
                ->field('id, username, truename')
                ->select();

            //短信发送
            $mobiles    = [];
            foreach($list as $item){
                if($item['username']){
                    $mobiles[]  = $item['username'];
                }
            }
            $AliyunMNS  = new \Common\Util\AliyunMNS();
            $AliyunMNS->sendVipWillEnd($mobiles);
            
        }catch(\Exception $e){
            write('./Log/error.log', 'Crontab:NotifyVipWillEnd', $e->getMessage);
        }

        S($this->lockName, null); 
    }

    // /**
    //  * 清空用户未支付课程订单
    //  * 每天运行一次
    //  */
    // function clearNoPayOrder(){
    //     //清除课程订单
    //     $list   = M('t_user_course', null)
    //         ->where('status = 2')
    //         ->select();

    //     $ids    = array();
    //     $moneyIds   = array();
    //     foreach($list as $val){
    //         $ids[]  = $val['id'];
    //         $moneyIds[]     = $val['pay_money_id'];
    //     }

    //     $ids    = implode(',', $ids);
    //     $moneyIds   = implode(',', $moneyIds);

    //     M('t_user_course', null)->where('id in (%s)', $ids)->delete();
    //     M('t_money', null)->where('id in (%s)', $moneyIds)->delete();

    //     S($this->lockName, null);
    // }

    /**
     * 收入报表统计
     * 每天统计1次
     */
    function createReportIncome($time = false){
        $time   = $time ? $time : strtotime(date('Y-m-d').' -1 day');
        $timeE  = $time + 3600*24 -1;
        
        $data   = M('t_money', null)
            ->where('status = 1 and create_time >= %d and create_time <= %d and amount > 0', $time, $timeE)
            ->field('sum(amount) income, sum(deduct) deduct')
            ->find();
        
        $data['time']   = $time;
        $data['profit'] = $data['income'] - $data['deduct'];
        $isExt  = M('t_report_income', null)->where('time = %d', $time)->find();
        if($isExt){
            $reportId   = $isExt['id'];
            M('t_report_income', null)->save($data);
        }else{
            $reportId  = M('t_report_income', null)->add($data);
        }
        
        //日志记录
        write_log('./Log/crontab.log', 't_report_income', 'report_success:'.$reportId);
        S($this->lockName, null);
    }

    /**
     * 课程售出统计
     * 每天运行一次
     */
    function createReportCourse($time = false){
        $time   = $time ? $time : strtotime(date('Y-m-d').' -1 day');
        $timeE  = $time + 3600*24 -1;

        $data   = M('t_user_course a', null)
            ->join('left join t_money b on a.get_relate_id = b.id')
            ->where('a.status = 1 and a.get_type = 1 and a.create_time >= %d and a.create_time <= %d', $time, $timeE)
            ->group('a.course_id')
            ->field('a.course_id, count(a.id) count, sum(b.amount) amount')
            ->select();

        if(!$data)
            $data[]   = array('course_id' => 0, 'count' => 0, 'amount' => 0);
        foreach($data as &$item){
            $item['time']   = $time;
        }
        
        //删除原有数据
        M('t_report_course', null)->where('time = %d', $time)->delete();
        //添加数据
        M('t_report_course', null)->addAll($data);
        //日志记录
        write_log('./Log/crontab.log', 't_report_course', 'report_success');
        S($this->lockName, null);
    }
    
    /**
     * 用户分红统计
     * 每天运行一次
     */
    function createReportUserDeduct($time = false){
        $timeS  = $time ? $time : strtotime(date('Y-m-d').' -1 day');
        $timeE  = $timeS + 3600*24 -1;

        $list   = M('t_deduct', null)
            ->where('create_time >= %d and create_time <= %d', $timeS, $timeE)
            ->group('user_id')
            ->field('user_id, sum(amount) amount')
            ->select();

        if(!$list)  return true;
        foreach($list as &$val){
            $val['time']    = $timeS;
            $val['date']    = date('Y-m-d H:i:s', $timeS);
        }
        //删除与原有数据
        M('t_report_user_deduct', null)->where('time = %d', $timeS)->delete();
        //添加新数据
        M('t_report_user_deduct', null)->addAll($list);

        //日志记录
        write_log('./Log/crontab.log', 't_report_user_deduct', 'report_success');
        S($this->lockName, null);
    }

    /**
     * 处理支付分成
     * 没5分钟运行一次
     */
    function doMoneyDeduct(){
        $moneys     = M('t_money', null)->where('status = 9')->select();
        $result     = array();
        foreach($moneys as &$moneyInfo){
            // if($moneyInfo['amount'] <= 0)   continue;
            // //现金分红操作
            // $info['money_info'] = $moneyInfo;
            // $info['resullt']    = D('Money')->relaRebate($moneyInfo);
            // $result[]   = $info;
            
            //交易完成后续处理
            D('Money')->successPaySequel($moneyInfo);
            $info['money_info'] = $moneyInfo;
            $info['result'] = D('Money')->errMsg;
        }

        write_log('./Log/crontab.log', 'do_money_deduct', $result);
        S($this->lockName, null);
    }

    /**
     * 推送微信模板消息队列
     * 每五分钟推送一次
     */
    function pushWxTempMsg(){
        $queueKey   = 'xinletu_wechat_message_queue';
        $redis      = \Common\Util\Redis::getInstance();
        $wxTempMsg  = \Wechat\Util\WxTempMsg::getInstance();
        $result     = array();

        while(true){
            $info   = $redis->lpop($queueKey);
            if(!$info)  break;
            $info   = json_decode($info, true);
            switch($info['msg_cate']){
                case 1:
                    $ret    = $wxTempMsg->sendScoreTempMsg(
                        $info['user_info'],
                        $info['score'],
                        $info['type'],
                        false
                    );
                break;
                case 2:
                    $ret    = $wxTempMsg->changeRole(
                        $info['id'],
                        $info['user_info'],
                        $info['old_role'],
                        false
                    );
                break;
                case 3:
                    $ret    = $wxTempMsg->withdraw(
                        $info['user_info'],
                        $info['wd_info'],
                        $info['success'],
                        false 
                    );
                break;
                case 4:
                    $ret    = $wxTempMsg->buyCourse(
                        $info['user_info'],
                        $info['course_info'],
                        $info['pay_info'],
                        false 
                    );
                break;
                case 5:
                    $ret    = $wxTempMsg->changeFather(
                        $info['user_info'],
                        $info['father_info'],
                        false
                    );
                break;
                case 6:
                    $ret    = $wxTempMsg->addChild(
                        $info['user_info'],
                        $info['child_info'],
                        false
                    );
                break;
                default: $ret   = $info; break;
            }
            $result[]   = $ret;
        }
        
        //日志记录
        write_log('./Log/crontab.log', 'push_wechat_message', $result);
        S($this->lockName, null);
    }

    /**
     * 购物车数据统计
     * 每天运行一次
     */
    function createReportShopCart(){
        $time   = strtotime(date('Y-m-d', strtotime('-1 day')));
        $timeE  = $time + 3600*24;

        $info   = M('t_shop_cart', null)
            ->where('create_time >= %d and create_time < %d and status = 1', $time, $timeE)
            ->field('count(*) count, sum(amount) amount')
            ->find();
        $info['time']   = $time;

        $isExt  = M('t_report_shopcart', null)->where('time = %d', $time)->find();
        if($isExt){
            $info['id'] = $isExt['id'];
            M('t_report_shopcart')->save($info);
        }else{
            M('t_report_shopcart')->add($info);
        }

        S($this->lockName, null);
    }
}